package cn.xenosp.server.common.system.impl;

import cn.xenosp.server.common.tools.ServiceUtil;
import cn.xenosp.server.common.system.AbstractTargetOperatingSystem;
import cn.xenosp.server.module.third_server.entity.NginxEntity;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 项目名： nginx-web
 * 包路径： cn.xenosp.nginx.common.system.impl
 * 作者：   TongHui
 * 创建时间: 2024-07-25 16:34
 * 描述: TODO
 * 版本: 1.0
 */
@Slf4j
public class LinuxSystem extends AbstractTargetOperatingSystem {

//    private Logs logs = Logs.getInstance("Linux 日志信息",LinuxSystem.class);

    private static final String USER_HOME = "/usr/local/web/nginx";
    private static final String START = "start.sh";
    private static final String STOP = "stop.sh";
    private static final String RESTART = "restart.sh";

    @Override
    public void createScript(String serverName,String startPaht,String configPath) {

        File nginx = new File(USER_HOME);
        if (!nginx.exists()){
            nginx.mkdirs();
            String script =  "#!/bin/bash\n ps aux | grep nginx";
            String path = USER_HOME+File.separator+"status.sh";
            // 使用try-with-resources语句自动关闭资源
            try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(path), StandardCharsets.UTF_8))) {
                // 写入脚本内容到文件
                writer.write(script);
                Runtime.getRuntime().exec("chmod +x "+path);
            } catch (IOException e) {
                e.printStackTrace();
                log.error("创建启动脚本文件时发生错误",e);
            }
        }
        nginx = new File(USER_HOME+File.separator+serverName);
        if (!nginx.exists()){
            nginx.mkdirs();
        }

        createStartScript(serverName, startPaht, configPath);
        createStopScript(serverName, startPaht, configPath);
        createRestartScript(serverName, startPaht, configPath);
    }


    private void createStartScript(String serverName,String startPaht,String configPath){
        String script =  "#!/bin/bash \n " +
                "program=" + startPaht + "\n " +
                "num=$(pgrep -c nginx) \n " +
                "if [ $num ge 0  ];then\n" +
                "  echo \"-1\"" +
                "\nelse\n" +
                "   $program -c "+configPath +
                "\nfi";
        String path = USER_HOME+File.separator+serverName+File.separator+serverName+"_"+START;
        // 使用try-with-resources语句自动关闭资源
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(path), StandardCharsets.UTF_8))) {
            // 写入脚本内容到文件
            writer.write(script);
            Runtime.getRuntime().exec("chmod +x "+path);
            log.info("启动脚本文件已创建");
        } catch (IOException e) {
            e.printStackTrace();
            log.error("创建启动脚本文件时发生错误",e);
        }
    }

    private void createStopScript(String serverName,String startPaht,String configPath){
        String script =  "#!/bin/bash\n" +
                "program=" + startPaht + "\n" +
                "num=$(pgrep -c nginx)\n" +
                "if [ $num -ge 1  ];then\n" +
                "   $program -s stop" +
                "\nelse\n" +
                "   echo \"-1\"" +
                "\nfi";
        String path = USER_HOME+File.separator+serverName+File.separator+serverName+"_"+STOP;
        // 使用try-with-resources语句自动关闭资源
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(path), StandardCharsets.UTF_8))) {
            // 写入脚本内容到文件
            writer.write(script);

            log.info("停止脚本文件已创建");
            Runtime.getRuntime().exec("chmod +x "+path);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("创建停止脚本文件时发生错误",e);
        }
    }

    private void createRestartScript(String serverName,String startPaht,String configPath){
        String script =  "#!/bin/bash\n" +
                "program=" + startPaht + "\n" +
                "num=$(pgrep -c nginx)\n" +
                "if [ $num -ge 1  ];then\n" +
                "   $program -s reload " +
                "\nelse\n" +
                "   echo \"-1\"" +
                "\nfi";
        String path = USER_HOME+File.separator+serverName+File.separator+serverName+"_"+RESTART;
        // 使用try-with-resources语句自动关闭资源
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(path), StandardCharsets.UTF_8))) {
            // 写入脚本内容到文件
            writer.write(script);

            log.info("停止脚本文件已创建");
            Runtime.getRuntime().exec("chmod +x "+path);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("创建停止脚本文件时发生错误",e);
        }
    }

    @Override
    public boolean isStartServer() {
        try {
            Thread.sleep(2000);
            log.info("查询服务进程===================");
            return ServiceUtil.isNginxRun();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean startServer(NginxEntity nginxEntity) throws Exception{
        try {
            log.info("开始执行启动脚本");
            String command = "/bin/bash "+USER_HOME+File.separator+nginxEntity.getServerName()+File.separator+nginxEntity.getServerName()+"_"+START;
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = input.readLine()) != null) {
                log.info("nginx 服务："+line);
            }
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                log.info("Nginx start successfully.");
            } else {
                log.info("Failed to start Nginx.");
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行启动脚本失败",e);
            throw  e;
        }
    }

    @Override
    public boolean stopServer(NginxEntity nginxEntity) throws Exception{
        try {
            log.info("开始执行停止脚本");
            String command = "/bin/bash "+USER_HOME+File.separator+nginxEntity.getServerName()+File.separator+nginxEntity.getServerName()+"_"+STOP;
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = input.readLine()) != null) {
                log.info("nginx 服务："+line);
            }
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                log.info("Nginx start successfully.");
            } else {
                log.info("Failed to start Nginx.");
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行启动脚本失败",e);
            throw  e;
        }
    }

    @Override
    public boolean restartServer(NginxEntity nginxEntity) throws Exception {
        try {
            log.info("开始执行重启脚本");
            String command = "/bin/bash "+USER_HOME+File.separator+nginxEntity.getServerName()+File.separator+nginxEntity.getServerName()+"_"+RESTART;
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = input.readLine()) != null) {
                log.info("nginx 服务："+line);
            }
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                log.info("Nginx start successfully.");
            } else {
                log.info("Failed to start Nginx.");
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行启动脚本失败",e);
            throw  e;
        }
    }

    @Override
    public String readConfig(String configPath) {
        try {
            log.info("读取配置文件");
            byte[] encoded = Files.readAllBytes(Paths.get(configPath));
            return new String(encoded, "GBK");
        } catch (IOException e) {
            e.printStackTrace();
            log.error("读取配置文件时错误",e);
            return null; // 或者抛出一个自定义的异常
        }
    }

    @Override
    public String readStart(NginxEntity nginxEntity) throws IOException {
        byte[] encoded = Files.readAllBytes(Paths.get(USER_HOME+File.separator+nginxEntity.getServerName()+File.separator+nginxEntity.getServerName()+"_"+START));
        return new String(encoded, StandardCharsets.UTF_8);
    }

    @Override
    public String readStop(NginxEntity nginxEntity)throws IOException  {
        byte[] encoded = Files.readAllBytes(Paths.get(USER_HOME+File.separator+nginxEntity.getServerName()+File.separator+nginxEntity.getServerName()+"_"+STOP));
        return new String(encoded, StandardCharsets.UTF_8);
    }

    @Override
    public String readRestart(NginxEntity nginxEntity) throws IOException {
        byte[] encoded = Files.readAllBytes(Paths.get(USER_HOME+File.separator+nginxEntity.getServerName()+File.separator+nginxEntity.getServerName()+"_"+RESTART));
        return new String(encoded, StandardCharsets.UTF_8);
    }

    @Override
    public void saveConfig(NginxEntity nginxEntity, String content, String type) {
        String path = "";
        switch (type){
            case "0":
                path = nginxEntity.getConfigPath();
                break;
            case "1":
                path =USER_HOME+File.separator+nginxEntity.getServerName()+File.separator+nginxEntity.getServerName()+"_"+START;
                break;
            case "2":
                path =USER_HOME+File.separator+nginxEntity.getServerName()+File.separator+nginxEntity.getServerName()+"_"+STOP;
                break;
            case "3":
                path =USER_HOME+File.separator+nginxEntity.getServerName()+File.separator+nginxEntity.getServerName()+"_"+RESTART;
                break;
        }
        log.info("修改配置文件："+path);
        writeConfig(path,content);
    }

}
